<?php
define('USER_SEX_MALE',		'M');
define('USER_SEX_FEMALE',	'F');
define('USER_TYPE_ADMIN',	'ADMIN');
define('USER_TYPE_USER',	'USER');
class UserPasswordException extends WException {}
class Cl_User extends WdkClass 
{
	protected
		/******************************************************/
		//	원본 테이블 정보
		/******************************************************/
		$user_seq			= 0					,	//	사용자 키값
		$user_type			= USER_TYPE_USER	,	//	사용자 로그인 아이디
		$user_login_id		= ''				,	//	사용자 로그인 아이디
		$user_login_passwd	= ''				,	//	로그인 비밀번호
		$fk_user_group_seq	= 0					,	//	그룹 키값
		$user_name			= ''				,	//	사용자명
		$user_nick			= ''				,	//	사용자 닉네임
		$user_icon			= ''				,	//	사용자 아이콘
		$user_photo			= ''				,	//	사용자 이미지
		$user_birth_date	= ''				,	//	생일
		$user_phone			= ''				,	//	연락처
		$user_mobile		= ''				,	//	핸드폰번호
		$user_email			= ''				,	//	이메일주소
		$user_sex			= USER_SEX_MALE		,	//	성별
		$user_memo			= ''				,	//	메모사항
		$user_info_public	= 'F'				,	//	정보 공개여부
		$user_validate_time	= 0					,	//	인증시간
		$user_insert_time	= 0					,	//	가입시간
		$user_del_flag		= 'F'				,	//	삭제여부
		/******************************************************/
		//	추가 정보
		/******************************************************/
		$user_group_name	= ''				,	//	그룹명
		$user_group_level	= 0					,	//	그룹레벨
		$user_group_icon	= ''				,	//	그룹아이콘
		$user_point			= 0					,	//	보유 포인트
		$user_login_time	= ''				,	//
		/******************************************************/
		//	추가 정보
		/******************************************************/
		$user_nick_str			= ''			,	//	
		$user_login_passwd_str	= ''			,	//	로그인 비밀번호
		$user_sex_str			= ''			,	//
		$user_info_public_str	= ''			;	//
	
	/**
	 * 	
	 */
	function __construct()
	{
		parent::__construct();
		self::getDbo();
	}
	
	/**
	 *	
	 */
	public function __init($data)
	{
		parent::__init($data);
		self::dformat();
	}
	
	/**
	 *	
	 */
	public function load($user_seq)
	{
		/*------------------------------------------------------------*/
		$dbo = self::getDbo();
		/*------------------------------------------------------------*/
		self::__init($dbo->cLoad($user_seq));
	}
	
	public function loadByLoginId($user_login_id)
	{
		/*------------------------------------------------------------*/
		$dbo = self::getDbo();
		/*------------------------------------------------------------*/
		self::__init($dbo->cLoadByLoginId($user_login_id));
	}
	
	public function loadByEmail($user_email)
	{
		/*------------------------------------------------------------*/
		$dbo = self::getDbo();
		/*------------------------------------------------------------*/
		self::__init($dbo->cLoadByEmail($user_email));
	}
	
	public function loadByNick($user_nick)
	{
		/*------------------------------------------------------------*/
		$dbo = self::getDbo();
		/*------------------------------------------------------------*/
		self::__init($dbo->cLoadByNick($user_nick));
	}
	
	/**
	 *	
	 */
	public function dformat()
	{
				
		list(	$this->user_mobile1,
				$this->user_mobile2,
				$this->user_mobile3) = @explode('-', $this->user_mobile);
		list(	$this->user_phone1,
				$this->user_phone2,
				$this->user_phone3) = @explode('-', $this->user_phone);
		list(	$this->user_birth_date1,
				$this->user_birth_date2,
				$this->user_birth_date3) = @explode('-', $this->user_birth_date);
		
		$pwd = Wdk::helper('Passwd');
		$this->user_login_passwd_str= $pwd->decrypt($this->user_login_passwd);
		$this->user_sex_str 		= $this->user_sex == 'M' ? '남성':'여성'; 
		$this->user_info_public_str = $this->user_info_public == 'T' ? '공개':'비공개';
		
		$this->user_nick_str = $this->user_nick;
		if($this->user_icon)
		{
			$this->user_nick_str = "<img src='{$this->user_icon}' class='user_icon'/>";
		}
		
		$this->user_insert_time_str = parent::timeString($this->user_insert_time);
	}
	
	/**
	 * 
	 */
	public function isApproved()
	{
		return $this->user_validate_time > 0; 
	}
	
	/**
	 * 
	 */
	public function autoUpdate($log='')
	{
		if((int)$this->user_seq > 0)
		{
			$this->update($log);
		}
		else
		{
			$this->insert($log);
		}
	}
	
	/**
	 *	
	 */
	public function insert($log='Insert')
	{
		/*------------------------------------------------------------*/
		$dbo = self::getDbo();
		$pwd = Wdk::helper('Passwd');
		
		/*------------------------------------------------------------*/
		$user=Wdk::get('User');
		try{$user->loadByLoginId($this->user_login_id);throw new WException("이미 사용중인 아이디입니다.");}catch(NoRecordException $e){}
		try{$user->loadByEmail($this->user_email);throw new WException("이미 사용중인 Email 입니다.");}catch(NoRecordException $e){}
		try{$user->loadByNick($this->user_nick);throw new WException("이미 사용중인 닉네임 입니다.");}catch(NoRecordException $e){}
		unset($user);
		/*------------------------------------------------------------*/
		$this->user_validate_time	= 0;
		$this->user_insert_time		= time();
		if($pwd->isEncryptable($this->user_login_passwd) == true)
		{
			$this->user_login_passwd	= $pwd->encrypt($this->user_login_passwd);
		}
		$this->user_del_flag		= 'F';
		
		$data = array(	'user_login_id'			=>	$this->user_login_id,
						'user_type'				=>	$this->user_type,
						'user_login_passwd'		=>	$this->user_login_passwd,
						'fk_user_group_seq'		=>	$this->fk_user_group_seq,
						'user_name'				=>	$this->user_name,
						'user_nick'				=>	$this->user_nick,
						'user_icon'				=>	$this->user_icon,
						'user_photo'			=>	$this->user_photo,
						'user_birth_date'		=>	$this->user_birth_date,
						'user_email'			=>	$this->user_email,
						'user_mobile'			=>	$this->user_mobile,
						'user_phone'			=>	$this->user_phone,
						'user_sex'				=>	$this->user_sex,
						'user_memo'				=>	$this->user_memo,
						'user_info_public'		=>	$this->user_info_public,
						'user_validate_time'	=>	$this->user_validate_time,
						'user_insert_time'		=>	$this->user_insert_time,
						'user_del_flag'			=>	$this->user_del_flag
					);
		$this->validate();
		$this->user_seq = $dbo->insert($data);
		/******************************************************/
		parent::setBackupData(array_keys($data));
		$this->backup($log);
		/******************************************************/
	}
	
	/**
	 *	
	 */
	public function join($log='Insert')
	{
		/*------------------------------------------------------------*/
		$dbo = self::getDbo();
		$pwd = Wdk::helper('Passwd');
		$ss = Wdk::get('SettingsManager');
		$settings = $ss->data();
		/*------------------------------------------------------------*/
		$user = Wdk::get('User');
		try{$user->loadByLoginId($this->user_login_id);throw new WException("이미 사용중인 아이디입니다.");}catch(NoRecordException $e){}
		try{$user->loadByEmail($this->user_email);throw new WException("이미 사용중인 Email 입니다.");}catch(NoRecordException $e){}
		try{$user->loadByNick($this->user_nick);throw new WException("이미 사용중인 닉네임 입니다.");}catch(NoRecordException $e){}
		unset($user);
		/*------------------------------------------------------------*/
		$this->user_validate_time	= 0;
		$this->user_insert_time		= time();
		if($pwd->isEncryptable($this->user_login_passwd) == true)
		{
			$this->user_login_passwd	= $pwd->encrypt($this->user_login_passwd);
		}
		$this->user_del_flag		= 'F';
		$this->fk_user_group_seq	= $settings['user_join_group'];
		
	
		$data = array(	'user_login_id'			=>	$this->user_login_id,
						'user_type'				=>	USER_TYPE_USER,
						'user_login_passwd'		=>	$this->user_login_passwd,
						'fk_user_group_seq'		=>	$this->fk_user_group_seq,
						'user_name'				=>	$this->user_name,
						'user_nick'				=>	$this->user_nick,
						'user_icon'				=>	$this->user_icon,
						'user_photo'			=>	$this->user_photo,
						'user_birth_date'		=>	$this->user_birth_date,
						'user_email'			=>	$this->user_email,
						'user_mobile'			=>	$this->user_mobile,
						'user_phone'			=>	$this->user_phone,
						'user_sex'				=>	$this->user_sex,
						'user_memo'				=>	$this->user_memo,
						'user_info_public'		=>	$this->user_info_public,
						'user_validate_time'	=>	$this->user_validate_time,
						'user_insert_time'		=>	$this->user_insert_time,
						'user_del_flag'			=>	$this->user_del_flag
					);
		$this->validate();
		$this->user_seq = $dbo->insert($data);
		/******************************************************/
		parent::setBackupData(array_keys($data));
		$this->backup($log);
		/******************************************************/
		
		$up = Wdk::get('UserPoint');
		$up->plus(	$this->user_seq,
					$settings['user_join_point'],
					"[가입포인트] {$this->user_attend_continue} "
				);
	}
	
	/**
	 * 
	 */
	public function update($log='update')
	{
		/*------------------------------------------------------------*/
		$dbo = self::getDbo();
		$pwd = Wdk::helper('Passwd');
		/*------------------------------------------------------------*/
		
		try
		{
			$user = Wdk::get('User');
			$user->loadByNick($this->user_nick);
			if($user['user_seq'] != $this->user_seq)
			{
				throw new WException("이미 사용중인 닉네임입니다.");
			}
			unset($user);
		}
		catch(NoRecordException $e){}
		
		if(parent::isUpdatable())
		{
			$data = array(	'fk_user_group_seq'		=>	$this->fk_user_group_seq,
							'user_type'				=>	$this->user_type,
							'user_name'				=>	$this->user_name,
							'user_nick'				=>	$this->user_nick,
							'user_icon'				=>	$this->user_icon,
							'user_photo'			=>	$this->user_photo,
							'user_birth_date'		=>	$this->user_birth_date,
							'user_email'			=>	$this->user_email,
							'user_mobile'			=>	$this->user_mobile,
							'user_phone'			=>	$this->user_phone,
							'user_sex'				=>	$this->user_sex,
							'user_memo'				=>	$this->user_memo,
							'user_info_public'		=>	$this->user_info_public
						);
			if($pwd->isEncryptable($this->user_login_passwd))
			{
				$this->user_login_passwd	= $pwd->encrypt($this->user_login_passwd);
				$data['user_login_passwd']	= $this->user_login_passwd;
			}
			$this->validate();
			$dbo->update($data, array("user_seq = ".$this->user_seq));
			/******************************************************/
			parent::setBackupData(array_keys($data));
			$this->backup($log);
			/******************************************************/
		}
	}
	
	/**
	 * 
	 */
	public function resetPasswd()
	{
		/*------------------------------------------------------------*/
		$dbo = self::getDbo();
		$pwd = Wdk::helper('Passwd');
		/*------------------------------------------------------------*/
		$user_login_passwd = utRc(8);
		$data = array(	'user_login_passwd'	=>	$pwd->encrypt($user_login_passwd));
		$dbo->update($data, array("user_seq = ".$this->user_seq));
		return $user_login_passwd;
	}
	
	/**
	 * 
	 */
	public function approve($log='approve')
	{
		/*------------------------------------------------------------*/
		$dbo = self::getDbo();
		/*------------------------------------------------------------*/
		if($this->isApproved()) return;
		
		$this->user_validate_time = time();
		
		$data = array(	'user_validate_time'	=>	$this->user_validate_time
					);
		$dbo->update($data, array("user_seq = ".$this->user_seq));
		/******************************************************/
		parent::setBackupData(array_keys($data));
		$this->backup($log);
		/******************************************************/
	}
	
	/**
	 * 
	 */
	public function delete($log='delete')
	{
		/*------------------------------------------------------------*/
		$dbo = self::getDbo();
		/*------------------------------------------------------------*/
		$dbo->delete(array("user_seq = ".$this->user_seq));
		/******************************************************/
		parent::setBackupData(array_keys($data));
		$this->backup($log);
		/******************************************************/
	}
	
	/**
	 *	
	 */
	public function login($login_id='', $login_passwd='')
	{
		$this->loadByLoginId($login_id);
		/*------------------------------------------------------------*/
		$pwd = Wdk::helper('Passwd');
		/*------------------------------------------------------------*/
		if( !$pwd->isEqual($this->user_login_passwd, $login_passwd))
		{
			throw new UserPasswordException("");
		}
		$user_login = Wdk::get("UserLogin");
		$user_login['fk_user_seq'] = $this->user_seq;
		$user_login->insert();
	}
	
	/**
	 *	
	 */
	private function validate()
	{
		if(strlen(trim($this->user_login_passwd)) < 6)
		{
			throw new WException("비밀번호는 6자 이상이여야 합니다.");
		}
		if(strlen(trim($this->user_login_id)) < 5 || strlen(trim($this->user_login_id)) > 12 || !preg_match("@([0-9a-z]*)@isU", $this->user_login_id))
		{
			throw new WException("아이디는 5자 이상 12자 이내의 영문소문자+숫자만 가능합니다.");
		}
		if(strlen(trim($this->user_name)) == 0)
		{
			throw new WException("이름이 공백이여서는 안됩니다.");
		}
	}
	
	/**
	 *	
	 */
	private function backup($log='')
	{
		/*------------------------------------------------------------*/
		$dbo = self::getDbo();
		/*------------------------------------------------------------*/
		$dbo->log($this->user_seq, $log, $this->backup_data);
	}
	
	/**
	 * 
	 */
	public function getDbo()
	{
		return Wdk::model(substr(__CLASS__, 3));
	}
}